﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace LibCom
{
    public class Connecting
    {

        public static Zug getZug(cardType[][] Board, cardType ShiftCard, treasureType Goal, int[] einschub, int[] Players)
        {
            int i, j;
            int axis_prev=-1, pos_prev=-1, dir_prev=-1, x,y;
            EnumsAndStructs.setPlayers(Players);
            Card[][] Cards = new Card[7][];
            for (i = 0; i < 7; i++)
            {
                Cards[i] = new Card[7];
                for (j = 0; j<7; j++)
                {
                    Cards[i][j] = EnumsAndStructs.convertCard(Board[i][j]);
                }
            }
            Card shiftCrd = EnumsAndStructs.convertCard(ShiftCard);
            y=einschub[0];
            x=einschub[1];
            if (x >= 0 && y >= 0)
            {
                if (x == 0 || x == 6)
                {
                    axis_prev = 0;
                    pos_prev = y / 2;
                    dir_prev = x == 0 ? 1 : 0;
                }
                else
                {
                    axis_prev = 1;
                    pos_prev = x / 2;
                    dir_prev = y == 0 ? 1 : 0;
                }
            }
            Treasure goal = EnumsAndStructs.convertTreasure(Goal);
            ret_Turn returned=getTurn(Cards, shiftCrd, axis_prev, dir_prev, pos_prev, goal);
            Zug ret = EnumsAndStructs.convertZug(returned, ShiftCard);
            return ret;
        }

        [DllImport("Library.dll", CallingConvention = CallingConvention.Cdecl)]
        static extern IntPtr getDraw(IntPtr[] Board, IntPtr crd, int axis_prev, int dir_prev, int pos_prev, Treasure goal);

        public static unsafe ret_Turn getTurn(Card[][] Board, Card ShiftCard, int axis_prev, int dir_prev, int pos_prev, Treasure goal)
        {
            int i, j;
            IntPtr[] brd = new IntPtr[7];
            for (i = 0; i < 7; i++)
            {
                int isizeofonestr = Marshal.SizeOf(typeof(Card));
                int itotalsize = 7 * isizeofonestr;
                brd[i] = Marshal.AllocHGlobal(itotalsize);
                byte* pret = (byte*)(brd[i].ToPointer());
                for (j = 0; j < 7; j++, pret += (isizeofonestr))
                {
                    IntPtr poneret = new IntPtr(pret);
                    Marshal.StructureToPtr(Board[i][j], poneret, false);
                }
            }
            IntPtr shiftCrd = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Card)));
            Marshal.StructureToPtr(ShiftCard, shiftCrd, false);
            IntPtr retPtr=getDraw(brd, shiftCrd, axis_prev, dir_prev, pos_prev,goal);
            ret_Turn ret= (ret_Turn) Marshal.PtrToStructure(retPtr, typeof(ret_Turn));
            foreach (var v in brd)
                Marshal.FreeHGlobal(v);
            return ret;
        }

    }
}
